package com.elitetyc.eliteim.client.thread;

import com.elitetyc.eliteim.client.EliteIMClient;
import com.elitetyc.eliteim.client.config.IMClientProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 重连服务
 * @Date 2021/9/17 13:37
 */
@Slf4j
public class ReConnectJob implements Runnable {

    /**
     * 当前已重试次数
     */
    private final AtomicInteger errorCount = new AtomicInteger(0);

    private final EliteIMClient eliteIMClient;

    private final ScheduledExecutorService scheduledExecutorService;

    private final IMClientProperties imClientProperties;

    public ReConnectJob(EliteIMClient eliteIMClient, ScheduledExecutorService scheduledExecutorService, IMClientProperties imClientProperties) {
        this.eliteIMClient = eliteIMClient;
        this.scheduledExecutorService = scheduledExecutorService;
        this.imClientProperties = imClientProperties;
    }

    @Override
    public void run() {
        try {
            if (eliteIMClient.nioSocketChannel != null && eliteIMClient.nioSocketChannel.isActive()) {
                // 如果还处于活跃状态，取消任务
                scheduledExecutorService.shutdown();
            } else {
                log.info("尝试第{}次重连--start", errorCount.get() + 1);
                eliteIMClient.reconnect();
            }
        } catch (Exception e) {
            errorCount.addAndGet(1);
            log.error("重连失败:{}", e.getMessage());
        } finally {
            if (errorCount.get() >= imClientProperties.getMaxReConnectCount()) {
                log.error("超过了最大重连次数，程序关闭");
                // 如果超过了最大重连次数
                scheduledExecutorService.shutdown();
                System.exit(-1);
            }
        }
    }
}
